import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable, { ellipsisRender } from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import DataForm from './components/DataForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import moment from 'moment';
import Bus from '../BusOrder/components/DetailDrawer';
import Sc from '../ScOrder/components/DetailDrawer';
import BusRefundPrice from '../BusOrder/components/refund/RefundPrice';
import BusRefundRecord from '../BusOrder/components/refund/RefundRecord';
import ScRefundPrice from '../ScOrder/components/refund/RefundPrice';
import ScRefundRecord from '../ScOrder/components/refund/RefundRecord';
import { areArraysEqual, arrayContrast } from '../BusOrder/stores/method';

const tableId = uniqueId('tauTable-');

const tabItems = [
  { key: '0', label: t`未处理异常车票` },
  { key: '1', label: t`平台退款车票` },
  { key: '2', label: t`已忽略` },
];

const order = {
  2: 'scOrder',
  3: 'busOrder',
};

const refund = {
  2: 'scRefund',
  3: 'busRefund',
};

const record = {
  2: 'scRecord',
  3: 'busRecord',
};

const Ticket = () => {
  const [modal, setModal] = useState();
  const [orderModal, setOrderModal] = useState([]);
  const { ticketStore: store } = useStore();
  const ticketRef = useRef();
  const [selectData, setSelectData] = useState([]);

  useEffect(() => {
    (async () => {
      await store.getCompany({ search: { isOperating: true }, pg: { size: 99, page: 0 } });
      // eslint-disable-next-line require-atomic-updates
      store._COMPANYS = store.company.reduce((acc, cur) => {
        const { label, value } = cur;
        acc[value] = label;
        return acc;
      }, {});
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { registerAddr, status, applicationRefundStatus: __, processingStatus: ___, getOnDate, getOnCar, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    const [fromTime, toTime] = getOnCar || [];
    const { applicationRefundStatus, processingStatus } = params.valueObjects;
    store.search = {
      registerAddr,
      status,
      from,
      to,
      fromTime,
      toTime,
      applicationRefundStatus: applicationRefundStatus ? [applicationRefundStatus.value] : [],
      processingStatus: processingStatus ? [processingStatus.value] : [],
      ...searchArgs,
    };
  };

  // 点击查看订单详情
  const handleViewTicket = (result) => {
    ticketRef.current = result;
    setOrderModal([order[result.orderType]]);
  };

  // 点击发起退款
  const handleOpenRefund = (result) => {
    const { orderType } = result;
    ticketRef.current = result;
    setOrderModal([refund[orderType]]);
  };

  // 点击查看退款详情
  const handleViewRecord = (result) => {
    const { orderType } = result;
    ticketRef.current = result;
    setOrderModal([record[orderType]]);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal();
  };

  // Modal窗口关闭回调
  const handleOrderCancel = () => {
    setOrderModal([]);
  };

  // 发起退款
  const handleOnRefund = async (result, state, type, account, otherAccount, _orderRefundStatus, open, store_account, store_initAccount) => {
    if (!_.isEmpty(result)) {
      try {
        let refundArgs = {};
        let args = {};
        const { id, cancelTime, refundPrice, distanceTime, cancelRemark = '', orderDetails, attachments, enableProfitShare } = toJS(result);
        const utcTime = moment.utc(cancelTime).subtract('8', 'hours').toISOString();
        /**
         * 退款逻辑 (退票和其他退款)
         * 1. 没有操作分账金额就给分账参数后端
         * 2. 页面上已经减去的退款金额要还原给后端
         * 3. 分账金额统一已 分 为单位
         */
        if (_orderRefundStatus === '0') {
          const numberAccount = account.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const computeAccount = arrayContrast(open, store_account, account);
          const equal = areArraysEqual(store_initAccount, numberAccount);
          const orderTicket = orderDetails?.filter((item) => item.check && !item.disabled);
          const newOrderTicket = orderTicket.map((item) => ({
            ...item,
            originalPrice: item.price,
          }));
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice).toFixed(2),
            distanceTime,
            cancelRemark,
            attachments: attachments || [],
            ticketRefundInfos: newOrderTicket,
            state,
            type,
            orderInfo: {
              orderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
          };
        } else if (_orderRefundStatus === '1') {
          const numberAccount = otherAccount.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const computeAccount = arrayContrast(store_account, otherAccount);
          const equal = areArraysEqual(store_initAccount, numberAccount);
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice).toFixed(2),
            distanceTime,
            cancelRemark,
            attachments: attachments || [],
            state,
            type,
            orderInfo: {
              orderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
          };
        } else {
          // 投诉索赔参数
          refundArgs = [{
            outTradeNo: id,
            amount: Number(refundPrice) * 100, // https://pm.aspiretop.com/issues/3178
            reason: cancelRemark,
            attachments: attachments || [],
            payType: '3',
          }];
        }
        if (_orderRefundStatus === '0' || _orderRefundStatus === '1') {
          await store.orderSponsorRefund(id, refundArgs, args);
        } else {
          // 线下支付 投诉索赔
          await store.orderCreateOffline(refundArgs);
        }
        Message.success({ content: t`申请退款成功` });
      } catch (e) {
        Message.error({ content: t`申请退款失败`, duration: 7000 });
        throw e;
      }
    }
    setOrderModal([]);
  };

  // 发起退款
  const handleOnRefundSc = async (result, state, type, account, otherAccount, _orderRefundStatus, open, store_account, store_initAccount) => {
    if (!_.isEmpty(result)) {
      try {
        let refundArgs = {};
        let args = {};
        const { id, cancelTime, refundPrice, distanceTime, cancelRemark = '', orderDetails, attachments, enableProfitShare } = toJS(result);
        const utcTime = moment.utc(cancelTime).subtract('8', 'hours').toISOString();
        /**
         * 退款逻辑 (退票和其他退款)
         * 1. 没有操作分账金额就给分账参数后端
         * 2. 页面上已经减去的退款金额要还原给后端
         * 3. 分账金额统一已 分 为单位
         */
        if (_orderRefundStatus === '0') {
          const numberAccount = account.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const computeAccount = arrayContrast(open, store_account, account);
          const equal = areArraysEqual(store_initAccount, numberAccount);
          const orderTicket = orderDetails?.filter((item) => item.checked && !item.disabled);
          const newOrderTicket = orderTicket.map((item) => ({
            ...item,
            originalPrice: item.ticketPrice,
          }));
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice).toFixed(2),
            distanceTime,
            cancelRemark,
            attachments: attachments || [],
            ticketRefundInfos: newOrderTicket,
            state,
            type,
            orderInfo: {
              orderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
          };
        } else if (_orderRefundStatus === '1') {
          const numberAccount = otherAccount.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const computeAccount = arrayContrast(open, store_account, otherAccount);
          const equal = areArraysEqual(store_initAccount, numberAccount);
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice).toFixed(2),
            distanceTime,
            cancelRemark,
            attachments: attachments || [],
            state,
            type,
            orderInfo: {
              orderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
          };
        } else {
          // 投诉索赔参数
          refundArgs = [{
            outTradeNo: id, // 订单id
            amount: Number(refundPrice) * 100, // 投诉索赔单位转化为分
            reason: cancelRemark,
            attachments: attachments || [],
            payType: '3', // 业务类型 约定给3
          }];
        }
        if (_orderRefundStatus === '0' || _orderRefundStatus === '1') {
          await store.orderSponsorRefund(id, refundArgs, args);
        } else {
          // 线下支付 投诉索赔
          await store.orderCreateOffline(refundArgs);
        }
        Message.success({ content: t`退款申请成功` });
      } catch (e) {
        Message.error({ content: t`退款申请失败`, duration: 7000 });
        throw e;
      }
    }
    setOrderModal([]);
  };

  /**
   * 处理忽略
   */
  const handleIgnore = async () => {
    if (selectData.length === 0) {
      return Message.warning({ content: t`请先勾选车票` });
    }
    Dialog.confirm({
      title: t`忽略车票`,
      content: t`确认忽略所选车票吗?`,
      onOk: async () => {
        try {
          const splitData = selectData.map((p) => {
            const [ticketCode, ___] = p.split('-');
            return ticketCode;
          });
          await store.ordersBatchTicket(splitData);
          Message.success({ content: t`忽略成功` });
        } catch (error) {
          Message.error({ content: t`忽略错误`, duration: 6000 });
        }
      },
    });
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`车票开始时间`, t`车票结束时间`],
            },
          },
          {
            name: 'getOnCar',
            type: 'date-range',
            props: {
              placeholder: [t`上车开始时间`, t`上车结束时间`],
            },
          },
          {
            name: 'orderType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.orderType),
              placeholder: t`订单类型`,
            },
          },
          {
            name: 'refundStatus',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.refundStatus),
              placeholder: t`运营商退款状态`,
              style: { width: 160 },
            },
          },
          {
            name: 'applicationRefundStatus',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.applicationRefundState),
              placeholder: t`平台退款状态`,
              style: { width: 160 },
            },
          },
          {
            name: 'processingStatus',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.processingState),
              placeholder: t`运营商处理状态`,
              style: { width: 160 },
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={store.orderStatus}
          onChange={(v) => {
            store.tickets = [];
            store.orderStatus = v;
          }}
          extra={store._orderStatus === '0' && <Button type="primary" onClick={() => handleIgnore()}>{t`一键忽略`}</Button>}
        >
          {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="key"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          sort={store.tableSort}
          rowSelection={store._orderStatus === '0' && {
            onChange: (e) => {
              setSelectData(e);
            },
            columnProps: () => {
              return {
                lock: 'right',
                width: 38,
                align: 'center',
              };
            },
          }}
          dataSource={toJS(store.tickets)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i, v) },
            column('orderId', { width: 188, cell: (v, _, r) => <Button type="primary" text onClick={() => handleViewTicket(r)}>{v}</Button> }),
            column('companyName', { width: 120 }),
            column('ticketCode', { width: 120 }),
            column('routeText', {
              width: 58,
              cell: (v, i, r) => {
                const { startMainAreaText, startMinorAreaText, endMainAreaText, endMinorAreaText } = r;
                return <>{ellipsisRender(`${startMainAreaText}-${startMinorAreaText} ~ ${endMainAreaText}-${endMinorAreaText}`)}</>;
              },
            }),
            column('passengerName', { width: 88 }),
            column('shiftTime', { width: 130, sortable: true }),
          ]
            .concat(store._orderStatus === '1' ? [
              column('applicationTime', { width: 130 }),
              column('applicationRefundState', { width: 130 }),
              column('processingState', { width: 150 }),
            ] : [])
            .concat([
              column('operatingState', { width: 110 }),
              column('operatorRefundTime', { width: 130, sortable: true }),
            ]).concat(store._orderStatus === '1' ? [column('refundTime', { width: 130 })] : []).concat([
              column('price', { width: 88 }),
            ]).concat(store._orderStatus === '0' ? [{
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 120,
              cell: (_, __, ticket) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenRefund(ticket)} >{t`退款`}</Button>
                </>),
            }] : [{
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 120,
              cell: (_, __, ticket) => (
                <>
                  <Button text type="primary" onClick={() => handleViewRecord(ticket)} >{t`查看退款详情`}</Button>
                </>),
            }])}
        />
      </div>
      <Bus
        modal={['view']}
        handleCancel={handleOrderCancel}
        handleUpdate={() => { }}
        orderId={ticketRef?.current?.orderId}
        visible={orderModal[0] === 'busOrder'}
        onClose={() => {
          setOrderModal(['view', `toClose$${Date.now()}`]);
        }}
      />
      <Sc
        modal={['view']}
        handleCancel={handleOrderCancel}
        handleUpdate={() => { }}
        orderId={ticketRef?.current?.orderId}
        visible={orderModal[0] === 'scOrder'}
        onClose={() => {
          setOrderModal(['view', `toClose$${Date.now()}`]);
        }}
      />
      <Drawer
        visible={modal?.visible === 'ticket'}
        title={t`查看 ${modal?.obj?.orderId} 退款申请`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="80%"
      >
        <DataForm
          partnerInfo={modal?.obj}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={() => { }}
        />
      </Drawer>
      <Drawer
        visible={orderModal[0] === 'busRefund'}
        title={t`巴士退款申请`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setOrderModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="90%"
      >
        <BusRefundPrice
          modal={['']}
          orderId={ticketRef.current?.orderId}
          onCancel={handleCancel}
          onSubmit={handleOnRefund}
        />
      </Drawer>
      <Drawer
        visible={orderModal[0] === 'scRefund'}
        title={t`专线退款申请`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setOrderModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="90%"
      >
        <ScRefundPrice
          modal={['']}
          order={ticketRef.current}
          onCancel={handleCancel}
          onSubmit={handleOnRefundSc}
        />
      </Drawer>

      <Drawer
        visible={orderModal[0] === 'busRecord'}
        title={t`查看巴士退款申请`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setOrderModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="90%"
      >
        <BusRefundRecord
          modal={['']}
          orderId={ticketRef.current?.orderId}
          onCancel={handleCancel}
          ticketCode={ticketRef.current?.ticketCode}
        />
      </Drawer>
      <Drawer
        visible={orderModal[0] === 'scRecord'}
        title={t`查看专线退款申请`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setOrderModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="90%"
      >
        <ScRefundRecord
          modal={['']}
          orderId={ticketRef.current?.orderId}
          onCancel={handleCancel}
          ticketCode={ticketRef.current?.ticketCode}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(Ticket);
